package cn.charlotte.pit.data.sub;

import cn.charlotte.pit.data.PlayerProfile;
import cn.charlotte.pit.data.deserializer.EnderChestDeserializer;
import cn.charlotte.pit.data.serializer.EnderChestSerializer;
import cn.charlotte.pit.util.MaterialConvert;
import cn.charlotte.pit.util.inventory.InventoryUtil;
import cn.charlotte.pit.util.item.ItemBuilder;
import cn.charlotte.pit.util.item.ItemUtil;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;

import java.util.Objects;

/**
 * @author EmptyIrony, Yurinan
 * @since 2020/12/29 23:05
 */

@JsonSerialize(using = EnderChestSerializer.class)
@JsonDeserialize(using = EnderChestDeserializer.class)
public class PlayerEnderChest {

    private Inventory inventory;
    private int rows;

    public PlayerEnderChest(int rows) {
        inventory = Bukkit.createInventory(null, rows * 9, "末影箱");
        this.rows = rows;
    }

    public static PlayerEnderChest deserialization(String string, int rows) {
        PlayerEnderChest enderChest = new PlayerEnderChest(rows);
        enderChest.getInventory().setContents(InventoryUtil.stringToItems(string));

        return enderChest;
    }

    public void openEnderChest(Player player) {
        player.closeInventory();

        PlayerProfile profile = PlayerProfile.getPlayerProfileByUuid(player.getUniqueId());
        int limit = getRows() * 9;

        for (int i = 27; i < this.inventory.getContents().length; i++) {
            if (i < limit && inventory.getItem(i) != null && ItemUtil.getInternalName(inventory.getItem(i)) != null && ItemUtil.getInternalName(inventory.getItem(i)).equalsIgnoreCase("not_unlock_slot")) {
                inventory.setItem(i, new ItemBuilder(Material.AIR).build());
            }
        }

        player.openInventory(inventory);
    }

    public String serialize() {
        int limit = 6 * 9;

        ItemStack[] itemStacks = new ItemStack[limit];
        for (int i = 0; i < limit; i++) {
            itemStacks[i] = inventory.getItem(i);
        }

        return InventoryUtil.itemsToString(itemStacks);
    }

    public Inventory getInventory() {
        return this.inventory;
    }

    public void setInventory(Inventory inventory) {
        this.inventory = inventory;
    }

    public int getRows() {
        return rows;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

}
